import {queryGroupTree} from '@/services/system/group/GroupService';
import {KfTreeNode, treeUtilsInstance, getEntityMemberValue} from 'kf-web-library';
import {useEventTarget} from 'ahooks';
import {Input, Spin, Tree} from 'antd';
import type {Key} from 'rc-tree/es/interface';
import React, {useEffect, useState} from 'react';
import "./GroupTree.less";
import * as API from "@/services";

export interface GroupTreeProps {
  selectedKey?: Key;
  onSelect?: (selectedKey: Key | undefined) => void;
}

const gNode: KfTreeNode = {
  id: '',
  key: '',
  title: <span>全部</span>,
  value: '',
  parentsId: [],
  parentsName: [],
};

const GroupTree: React.FC<GroupTreeProps> = (props) => {
  const [loading, setLoading] = useState<boolean>(true);
  const [treeData, setTreeData] = useState<KfTreeNode[]>([]);
  const [datasource, setDatasource] = useState<API.Group_TreeNode[]>([]);
  const [searchVal, {reset: searchValReset, onChange: searchValOnChange}] = useEventTarget({
    initialValue: '',
  });
  const [treeExpandedKeys, setTreeExpandedKeys] = useState<any[]>([]);

  const highlight = (keyword = '') => {
    const expandKeys: string[] = [];

    const nodes = treeUtilsInstance.filterNodes(treeUtilsInstance.mapNodes(
        datasource,
        (n) => {
          const index = n.name!.indexOf(keyword);
          const beforeStr = n.name!.substr(0, index);
          const afterStr = n.name!.substr(index + keyword.length);
          if (index > -1) {
            expandKeys.push(n.id.toString());
          }
          const rNode = {
            key: getEntityMemberValue(n, "id"),
            value: getEntityMemberValue(n, "id"),
            title: index > -1 ? (
                <span>{beforeStr}<span style={{color: '#f50'}}>{keyword}</span>{afterStr}</span>
            ) : (
                n.name
            ),
            parentsId: n.parentsId?.reverse(),
            parentsName: n.parentsName?.reverse(),
          } as KfTreeNode;
          return rNode;
        }
    ), node => {
      return true;
    }, 'breadth');

    nodes.splice(0, 0, gNode);
    setTreeData(nodes);
    setTreeExpandedKeys(expandKeys);
  };

  useEffect(() => {
    highlight(searchVal);
  }, [searchVal]);

  useEffect(() => {
    setLoading(true);
    queryGroupTree({})
        .then((resp) => {
          if (resp.flag) {
            setDatasource(resp.data);
            const expandKeys: string[] = [];
            const nodes = treeUtilsInstance.filterNodes(treeUtilsInstance.mapNodes(
                resp.data,
                (n) => {
                  const rNode = {
                    key: getEntityMemberValue(n, "id"),
                    value: getEntityMemberValue(n, "id"),
                    title: getEntityMemberValue(n, "name"),
                    parentsId: n.parentsId?.reverse(),
                    parentsName: n.parentsName?.reverse(),
                  } as KfTreeNode;
                  return rNode;
                }
            ), node => {
              if (node.parentsId?.length === 0) {
                expandKeys.push(node.key.toString());
              }
              return true;
            }, 'breadth');
            nodes.splice(0, 0, gNode);
            setTreeData(nodes);
            setTreeExpandedKeys(expandKeys);
          }
        })
        .finally(() => {
          setLoading(false);
        });
  }, []);

  const onSelect = (selectedKeys: Key[], info: any) => {
    if (props.onSelect) {
      props.onSelect(selectedKeys.length > 0 ? selectedKeys[0] : undefined);
    }
  };

  return (
      <Spin spinning={loading}>
        <div className={'kf-group-tree-search-wrap'}>
          <Input.Search style={{marginBottom: 8}} placeholder="组织名称" value={searchVal} onChange={searchValOnChange} allowClear/>
        </div>
        <Tree
            className={'kf-group-tree'}
            checkable={false}
            expandedKeys={treeExpandedKeys}
            onExpand={setTreeExpandedKeys}
            onSelect={onSelect}
            selectedKeys={props.selectedKey ? [props.selectedKey] : []}
            treeData={treeData}
            autoExpandParent
        />
      </Spin>
  );
};

export default GroupTree;
